import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "@/stores/user";

const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/Login.vue"),
    meta: { requiresGuest: true },
  },
  {
    path: "/dashboard",
    name: "Dashboard",
    component: () => import("@/views/Dashboard.vue"),
    meta: { requiresAuth: true },
    redirect: "/dashboard/customers",
    children: [
      {
        path: "home",
        name: "DashboardHome",
        component: () => import("@/views/DashboardHome.vue"),
      },
      {
        path: "customers",
        name: "CustomerManagement",
        component: () => import("@/views/CustomerManagement.vue"),
      },
      {
        path: "shops",
        name: "ShopManagement",
        component: () => import("@/views/ShopManagement.vue"),
      },
      {
        path: "networks",
        name: "NetworkManagement",
        component: () => import("@/views/NetworkManagement.vue"),
      },
      {
        path: "waybill-recharge",
        name: "WaybillRecharge",
        component: () => import("@/views/WaybillRecharge.vue"),
      },
      {
        path: "transaction-records",
        name: "TransactionRecords",
        component: () => import("@/views/TransactionRecords.vue"),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    if (!userStore.isLoggedIn()) {
      // 尝试验证令牌
      const isValid = await userStore.verifyToken();
      if (!isValid) {
        next("/login");
        return;
      }
    }
  }

  // 检查是否需要游客状态（如登录页）
  if (to.meta.requiresGuest && userStore.isLoggedIn()) {
    next("/dashboard");
    return;
  }

  next();
});

export default router;
